<!--
 * @Description: 第八章-导航守卫
 * @Author: IA ia@kepro.space
 * @Date: 2025-02-26 18:16:54
-->
<template>
    <!-- <loadingBar></loadingBar> -->
    <div class="login">

        <el-card class="box-card">
            <el-form ref="form" :rules="rules" :model="formInline" class="demo-form-inline">
                <el-form-item prop="user" label="账号">
                    <el-input v-model="formInline.user" placeholder="账号" />
                </el-form-item>
                <el-form-item prop="password" label="密码">
                    <el-input type="password" v-model="formInline.password" placeholder="密码" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">登录</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>


</template>
<script setup lang="ts">
import { reactive, ref } from 'vue'

import { useRouter } from 'vue-router';

import type { FormItemRule, FormInstance } from 'element-plus';
import { ElMessage } from 'element-plus'

// import loadingBar from '@/components/loadingBar.vue'


import axios from 'axios';

const router = useRouter()

type From = {
    user: string,
    password: string
}

type Rules = {
    [K in keyof From]?: Array<FormItemRule>
}

const formInline = reactive<From>({
    user: '',
    password: '',
})

const rules = reactive<Rules>({
    user: [{
        required: true,
        message: "请输入账号",
        trigger: 'blur'
    }],
    password: [
        {
            required: true,
            message: "请输入密码",
            trigger: 'blur'
        }
    ]
})

const form = ref<FormInstance>()

const onSubmit = () => {
    console.log('submit!')
    console.log('Login.vue onSubmit Form Value', form.value);
    form.value?.validate((validate) => {
        console.log('Login.vue onSubmit Form Value validate', validate);
        if (validate) {
            router.push('/index')
            localStorage.setItem('token', '1')
            initRouter()
        } else {
            ElMessage({
                type: 'error',
                message: '登录失败',
            })
        }
    }) 
}

const initRouter = async () => {
    const result = await axios.get('http://localhost:9999/router_study/login', {params:formInline})
    console.log('Login.vue initRouter result: ', result)
    result.data.route.forEach((v:any) => {
        router.addRoute({
            path: v.path,
            name: v.name,
            component: () => import(`../views/12th/${v.component}`)
        })
    })
}


</script>
<style scoped lang="less">
.login {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.scrollBehavior {
    width: 80%;
    height: 800px;
    margin: 0 10%;
    background-color: black;
    color: #fff;
    text-align: center;
    line-height: 1000px;
    font-size: 30px;
}
</style>